package com.fangcang.b2b.common.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.fangcang.b2b.common.controller.BaseController;
import com.fangcang.b2b.common.util.UrlUtil;
import com.fangcang.common.ResponseDTO;
import com.fangcang.common.enums.ErrorCodeEnum;
import com.fangcang.common.enums.ResultCodeEnum;
import com.fangcang.common.util.StringUtil;
import com.fangcang.message.remote.WxAuth2Remote;
import com.fangcang.message.remote.response.weixin.WxAuth2RedirectResponseDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private WxAuth2Remote wxAuth2Remote;

    /**
     * 复写preHandle属性
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String servletPath = request.getServletPath();
        log.debug("servletPath:" + servletPath);
        //创建初始化控制器
        BaseController bc = null;
        if (handler instanceof HandlerMethod) {
            Object bean=((HandlerMethod) handler).getBean();
            if (bean instanceof BasicErrorController){
                return super.preHandle(request, response, handler);
            }else{
                bc = (BaseController) ((HandlerMethod) handler).getBean();
            }
        } else {
            return super.preHandle(request, response, handler);
        }

        //如果是登录则路过或者支付
        if(servletPath!=null && (servletPath.endsWith("/login")
                || servletPath.endsWith("/wxBusDispatcher.shtml")
                || servletPath.endsWith("/wxPayNotify.shtml"))
                ){
            return true;
        }

        //如果openid为空，则跳转到微信获取用户信息
        if(UrlUtil.isWeixinBrowserVisit(request)
                &&  bc.getCacheVisitWxOpenId() == null){
            String wxSrcVisitUrl = request.getRequestURL()
                    + (StringUtils.isNotBlank(request.getQueryString())?"?"+request.getQueryString():"");
            bc.setWxSrcVisitUrl(wxSrcVisitUrl);

            //业务分发URL
            String url = "http://"+request.getServerName()+"/b2b-app/b2b/wxBusDispatcher.shtml";
            //腾讯端微信请求URL
            try{
                ResponseDTO<WxAuth2RedirectResponseDTO> auth2Response = wxAuth2Remote.auth2Redirect(url);
                if(auth2Response.getResult()== ResultCodeEnum.FAILURE.code
                        || auth2Response.getModel()==null){
                    writeResponse(request,response,ResultCodeEnum.FAILURE.code,ErrorCodeEnum.LOGIN_EXCEPTION.errorNo,ErrorCodeEnum.LOGIN_EXCEPTION.errorDesc);
                    return false;
                }
                url = auth2Response.getModel().getRedirectUrl();
            }catch(Exception e){
                log.error("获取auth2Redirect地址失败");
                writeResponse(request,response,ResultCodeEnum.FAILURE.code,ErrorCodeEnum.LOGIN_EXCEPTION.errorNo,ErrorCodeEnum.LOGIN_EXCEPTION.errorDesc);
                return false;
            }
            String type = request.getHeader("x-requested-with");// XMLHttpRequest
            if ("XMLHttpRequest".equalsIgnoreCase(type)
                    || (StringUtil.isValidString(request.getContentType()) && request.getContentType().indexOf("json")>0)
                    ) {// ajax请求
                if(request.getHeader("OriginUrl")!=null){
                    bc.setWxSrcVisitUrl(request.getHeader("OriginUrl"));
                }else{
                    bc.setWxSrcVisitUrl(request.getHeader("Origin"));
                }
                writeResponse(request,response,ResultCodeEnum.FAILURE.code,"redirect",url);
            } else {
                response.sendRedirect(url);
            }
            return false;
        }

        //如果没登录则返回
        if(bc.getCacheUser()==null){
            writeResponse(request,response,ResultCodeEnum.FAILURE.code,"unlogin","用户未登录");
            return false;
        }
        return super.preHandle(request, response, handler);
    }

    private void writeResponse(HttpServletRequest request,HttpServletResponse response,int result,String errorNo, String errorMsg) throws IOException {
        ResponseDTO res = new ResponseDTO();
        res.setResult(result);
        res.setFailCode(errorNo);
        res.setFailReason(errorMsg);

        String type = request.getHeader("x-requested-with");// XMLHttpRequest
        if ("XMLHttpRequest".equalsIgnoreCase(type)
                || (StringUtil.isValidString(request.getContentType()) && request.getContentType().indexOf("json")>0)
                ) {// ajax请求
            // 指定允许其他域名访问
            response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(JSONObject.toJSONString(res));
        }else{

        }
    }
}
